#  压缩图片大小
#
#
import os
import datetime,time
import python_tools

def traverse_dir(init_path):
    list_path =[init_path,]
    postfix=['.png','.jpg']
    new_postfix = ['_XT%s'%pf for pf in postfix]
    over_days =3    #图片过期时间,以天为单位
    while list_path:
        cur_path = list_path.pop()
        files = os.listdir(cur_path)
        for f in files:
            next_path = cur_path+'/'+f
            if os.path.isdir(next_path):
                list_path.append(next_path)
            elif os.path.isfile(next_path):
                days_ago = (datetime.datetime.now()-datetime.datetime.fromtimestamp(os.path.getctime(next_path))).days
                if days_ago>over_days:  #删除过期图片
                    os.system('rm %s'%next_path)

                # 去除压缩后的小图或已有小图的大图
                if ('_XT' in f) or ('%s_XT.jpg' % f[:-4] in files) or ('%s_XT.png' % f[:-4] in files):
                    continue
                for pf in new_postfix:
                    if '%(filename)s%(postfix)s'%{'filename':f[:-4],'postfix':pf} in files:
                        continue
                compress(next_path)
                print(next_path)

def compress(pth):
    cmd ='pngquant -f --quality 10 %(pth)s.%(postfix)s -o %(pth)s_XT.%(postfix)s'%{'pth':pth[:-4],'postfix':pth[-3:]}
    print(cmd)
    os.system(cmd)

@python_tools.error_reporter('10.116.52.5','yasuo')
@python_tools.apply_source_change
def one_run(dir_name):
    traverse_dir(dir_name)
    for i in range(-5,1):
        print(1/i)
        time.sleep(3)



